package com.ctg.itrdc.imageconsole.control.ssh.utils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * sets authorized keys on systems with given refresh interval
 */
public class RefreshAuthKeyUtil {


	private Timer timer;
	private static Integer minute = Integer.valueOf(AppConfig.getProperty("authKeysRefreshInterval"));


	private RefreshAuthKeyUtil() {
		//set interval
		timer = new Timer();
		timer.schedule(new RefreshAllSystemsTimerTask(), minute * 60 * 1000);
	}

	/**
	 * start timer to refresh all systems
	 */
	public static void startRefreshAllSystemsTimerTask() {
		if (SSHUtil.keyManagementEnabled && minute > 0) {
			new RefreshAuthKeyUtil();
		}
	}

	/**
	 * Task for distributing keys to all systems
	 */
	public static void refreshAllSystems() {

		Runnable run = new RefreshAllSystemsTask();
		Thread thread = new Thread(run);
		thread.start();
	}
	/**
	 * Timer task for distributing keys to all systems
	 */
	private class RefreshAllSystemsTimerTask extends TimerTask {

		@Override
		public void run() {
			//distribute all public keys
			SSHUtil.distributePubKeysToAllSystems();
			timer.cancel();

			//create new timer and set interval
			timer = new Timer();
			timer.schedule(new RefreshAllSystemsTimerTask(), minute * 60 * 1000);
		}
	}

}


/**
 * Task for distributing keys to all systems
 */
class RefreshAllSystemsTask implements Runnable {

	@Override
	public void run() {
		//distribute all public keys
		SSHUtil.distributePubKeysToAllSystems();

	}
}
